const http = require('http');
const data = require('./data/index.json');
let app = http.createServer((req, res) => {
    res.setHeader('content-type', 'text/html;charset=utf-8');
    let {pathname,searchParams} = new URL(req.url,'http://localhost');
    if (pathname === '/list' || pathname === '/') {
        let str = `
        <h3>新闻列表</h3>
        <ul>
            ${data.map(obj =>
            `<li><a href="/detail?id=${obj.id}">${obj.newsTitle}</a></li>`
        ).join('')}
        </ul>`;
        res.end(str);
    }else if( pathname === '/detail'){
        let id = searchParams.get('id');
        let obj =  data.find(obj=>obj.id === id);

        if(!obj){
            // 不存在
            res.end('抱歉，您访问新闻已不存在');
            return;
        }

        let str = `
            <a href="/list"><返回</a>
            <h3>${obj.newsTitle}</h3>
            <p>${obj.newsContent}</p>
        `;
        res.end(str);
    }
    else{
        res.end('404');
    }
})
app.listen(80, () => {
    console.log("80启动成功");
})